//
//  ARAudioPlayerManager.m
//  AwesomeRecorder
//
//  Created by Xing on 2019/11/29.
//  Copyright © 2019 Xing. All rights reserved.
//

#import "ARAudioPlayerManager.h"
#import <AVFoundation/AVFoundation.h>
#import "CRHeader.h"

@interface ARAudioPlayerManager()<AVAudioPlayerDelegate>

proStrong AVAudioPlayer *player;

@end

@implementation ARAudioPlayerManager

+ (instancetype)sharedInstance {
    
    static dispatch_once_t once;
    static id __singleton__;
    dispatch_once( &once, ^{ __singleton__ = [[self alloc] init]; });
    return __singleton__;
}

- (void)startWithPath:(NSString *)path {
    
    if (self.isPlaying) {
        return;
    }
    
    if (self.player) {
        [self.player stop];
        self.player = nil;
    }
    
    //获取录音数据
    NSData * wavData = [NSData dataWithContentsOfFile:path];
    NSError * error;
    //    AVAudioPlayer * player = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:&error];
    self.player = [[AVAudioPlayer alloc]initWithData:wavData error:&error];
    self.player.delegate = self;
    if (error) {
        NSLog(@"语音播放失败,%@",error);
        return;
    }
    //播放器的声音会自动切到receiver，所以听起来特别小，如果需要从speaker出声，需要自己设置。
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:&error];
    // 单独设置音乐的音量（默认1.0，可设置范围为0.0至1.0，两个极端为静音、系统音量）：
    self.player.volume = 1.0;
    //    修改左右声道的平衡（默认0.0，可设置范围为-1.0至1.0，两个极端分别为只有左声道、只有右声道）：
    //self.player.pan = -1;
    //    设置播放速度（默认1.0，可设置范围为0.5至2.0，两个极端分别为一半速度、两倍速度）：
    self.player.rate = 1.0;
    //    设置循环播放（默认1，若设置值大于0，则为相应的循环次数，设置为-1可以实现无限循环）：
    //self.player.numberOfLoops = 1;
    self.player.currentTime = 0;
    //调用prepareToPlay方法，这样可以提前获取需要的硬件支持，并加载音频到缓冲区。在调用play方法时，减少开始播放的延迟。
    [self.player prepareToPlay];
    //    开始播放音乐：
    [self.player play];
    
    self.isPlaying = YES;
}

- (void)stop {
    
    if (self.player) {
        [self.player stop];
        self.player = nil;
    }
    
    self.didFinishAction = nil;
    
    self.isPlaying = NO;
}

- (void)pause {
    
    [self.player pause];
    
    self.isPlaying = NO;
}

- (void)play {
    
    [self.player play];
    
    self.isPlaying = YES;
}

- (NSTimeInterval)currentTime {
    
    return [self.player currentTime];
}

#pragma mark -
#pragma mark AVAudioPlayerDelegate

//播放完成代理
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
    
    if (self.didFinishAction) {
        self.didFinishAction();
    }
    
    [self stop];
}

- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError * __nullable)error {
    
    [self stop];
}

@end
